package com.itlong.cloud.app.service.impl;

import com.itlong.cloud.POJO.VO.app.engineer.AppEngineerUserInfoVO;
import com.itlong.cloud.POJO.VO.app.engineer.AppEngineerUserOwnProjectVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppEngineerLoginDao;
import com.itlong.cloud.app.service.IAppEngineerService;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <desc>
 *      工程版APP接口实现类。
 * <desc/>
 *
 * @createDate 2017/11/6.
 */
@Service
@RefreshScope
public class AppEngineerServiceImpl implements IAppEngineerService {

    @Autowired
    IAppEngineerLoginDao iAppEngineerLoginDao;  //工程版APP登录

    @Autowired
    private RedisService<AppEngineerUserInfoVO> redisService;

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;

    /**
      * <desc>
      *      工程版APP登录。
      * <desc/>
      *
      * @param userInfoPO
      * @return AppUserCacheVO
      * @author shengen.T
      * @createDate 2017/11/6
      */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public AppEngineerUserInfoVO logEngineerLoginInfo(AppEngineerUserInfoVO userInfoPO) throws  Exception{
        if (userInfoPO!=null){
            String token = UserTokenUtil.tokenEncrypt(userInfoPO.getUserId(),APP_USER_TOKEN_KEY, SystemTypeEnum.IOS.getType());
            userInfoPO.setPassword(null);
            userInfoPO.setToken(token);
            List<AppEngineerUserOwnProjectVO> projectList = getUserOwnProjectInfo(userInfoPO.getUserId());
            userInfoPO.setProjects(projectList);
            userInfoPO.setPhoneNo(userInfoPO.getPhoneNo());
            redisService.set(RedisConstant.APP_LOGIN+userInfoPO.getUserId(),RedisConstant.APP_USER_TOKEN_TIME,userInfoPO);
            return userInfoPO;
        }
        return null;
    }

    /**
     * <desc>
     *      获取工程版APP登录信息。
     * <desc/>
     *
     * @param  phoneNo 工程人员账号
     * @return
     * @author shengen.T
     * @createDate 2018-01-20
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public AppEngineerUserInfoVO getEngineerAppUserLogin(String phoneNo) throws Exception{
        AppEngineerUserInfoVO userInfoVO = iAppEngineerLoginDao.engineerAppUserLogin(phoneNo);
        return  userInfoVO;
    }

    /**
     * <desc>
     *      验证工程账号权限信息。
     * <desc/>
     *
     * @param  userId 用户ID
     * @return
     * @author shengen.T
     * @createDate 2018-01-20
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public Integer checkEngineerLogin(String userId) throws Exception{
        return iAppEngineerLoginDao.checkEngineer(userId);
    }

    /**
     * <desc>
     *     APP端登录获取用户项目列表信息
     * </desc>
     *
     * @param userId  用户ID
     * @return  APP用户所拥有的项目配置信息的集合
     * @author shengen.T
     * @createDate 2017/11/6
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public List<AppEngineerUserOwnProjectVO> getUserOwnProjectInfo(String userId) throws Exception{
        List<AppEngineerUserOwnProjectVO> projectInfoList = iAppEngineerLoginDao.getProjectInfo(userId);
        return  projectInfoList;
    }


    /**
     * <desc>
     *      从缓存获取用户信息
     * </desc>
     *
     * @param token
     * @return
     * @author shengen.T
     * @createDate 2017/11/8
     */
    @Override
    public AppEngineerUserInfoVO retrieve(String token) {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(token, APP_USER_TOKEN_KEY);
            if (userId == null) {
                return null;
            }
            AppEngineerUserInfoVO userInfo = redisService.getObject(RedisConstant.APP_LOGIN+userId, AppEngineerUserInfoVO.class);
            if (userInfo != null && token.equals(userInfo.getToken())) {
                return userInfo;
            } else {
                return null;
            }
        }catch (RedisConnectionFailureException e){
            throw new DataAccessException("工程版APP_retrieve【从缓存中获取用户信息】redis连接失败") ;
        }
    }

    /**
     * <desc>
     *     工程版APP,更新密码
     * </desc>
     * @param userId
     * @param oldPswd 加密后的旧密码
     * @param currentPswd 加密后的新密码
     * @return
     * @author shengen.T
     * @createDate 2017/10/11
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer updatePswd(String userId,String oldPswd,String currentPswd){
        Integer result=0;
        String password = iAppEngineerLoginDao.getPswd(userId);
        if(!oldPswd.equals(password)){
            return result;
        }
        result =  iAppEngineerLoginDao.updatePswd(userId,currentPswd);
        return result;
    }

}
